package com.fintech.third.utils.shzx;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import org.springframework.web.multipart.MultipartFile;

import com.fintech.third.model.ThirdProperties;
import com.fintech.third.utils.ThirdPropertiesInitUtil;
import com.marvels.common.utils.MarvelsLogUtil;

import de.idyl.winzipaes.AesZipFileEncrypter;
import de.idyl.winzipaes.impl.AESEncrypterBC;

public class ZipUtils {

    private static String orgcode = "Q10155800HOQ00";//机构名称
  
    
	/**
	 * 将文件压缩成zip格式
	 * @param file
	 * @param request
	 * @return
	 */
	public static File zipFile(MultipartFile file) {
		 ThirdProperties thirdProperties=ThirdPropertiesInitUtil.getThirdProperties();
		 String realsavepath=WriteDataUtil.class.getResource(thirdProperties.getImage_path()).getPath();
		//String realsavepath = request.getSession().getServletContext().getRealPath("");
		String name = file.getOriginalFilename().substring(0,
				file.getOriginalFilename().length() - file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).length());
		String filePath = realsavepath + "temp\\" + "zip\\" + name + "_zip.zip";
		String zipFilePath = realsavepath + "temp\\" + "zip\\";
		File zipFile = fileCreate(filePath, zipFilePath);
		ZipOutputStream out = null;
		try {
			out = new ZipOutputStream(new FileOutputStream(zipFile));// ����ѹ���ļ�·�����õ�ѹ����

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		byte[] buffer = new byte[1024];
		MultipartFile[] file1 = {file};
		for (int x = 0; x < file1.length; x++) {
			InputStream fis;
			int len;
			try {
				fis = file1[x].getInputStream();
				out.putNextEntry(new ZipEntry(file1[x].getOriginalFilename()));
				while ((len = fis.read(buffer)) > 0) {
					out.write(buffer, 0, len);
				}
				out.closeEntry();
				fis.close();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return zipFile;

	}
	
	
	/**
	 * 将文件压缩成zip格式
	 * @param file
	 * @param request
	 * @return
	 */
	public static File zipFile(File file) {
		 ThirdProperties thirdProperties=ThirdPropertiesInitUtil.getThirdProperties();
		 String realsavepath=WriteDataUtil.class.getResource(thirdProperties.getImage_path()).getPath();
		//String realsavepath = request.getSession().getServletContext().getRealPath("");
		String name = file.getName().substring(0,file.getName().lastIndexOf("."));
		if(!new File(realsavepath+"temp").exists()){
			new File(realsavepath+"temp").mkdirs();
		}
		String filePath = realsavepath + "temp/" + "zip/" + name + ".zip";
		String zipFilePath = realsavepath + "temp/" + "zip";
		File zipFile = fileCreate(filePath, zipFilePath);

		ZipOutputStream out = null;
		try {
			out = new ZipOutputStream(new FileOutputStream(zipFile));// ����ѹ���ļ�·�����õ�ѹ����

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		byte[] buffer = new byte[1024];
		File[] file1 = {file};
		for (int x = 0; x < file1.length; x++) {
			FileInputStream fis;
			int len;
			try {
				fis = new FileInputStream(file1[x]);
				out.putNextEntry(new ZipEntry(file1[x].getName()));
				while ((len = fis.read(buffer)) > 0) {
					out.write(buffer, 0, len);
				}
				out.closeEntry();
				fis.close();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return zipFile;

	}

	/**
	 * 加密zip文件
	 * @param zipFile
	 * @param passWord
	 * @param request
	 * @return
	 */

	public static File encryptZipFile(File zipFile, String passWord) {
		 ThirdProperties thirdProperties=ThirdPropertiesInitUtil.getThirdProperties();
		 String realsavepath=WriteDataUtil.class.getResource(thirdProperties.getImage_path()).getPath();
		String prefix=zipFile.getName().substring(zipFile.getName().lastIndexOf("."));//获取后缀
		MarvelsLogUtil.getInstance().info("==========>>>>>>文件后缀名:"+prefix);
		if(!prefix.contains("zip")){
			return null;
		}
		//String realsavepath = request.getSession().getServletContext().getRealPath("");
		String desFile = realsavepath + "temp/" + "encrypt/" + zipFile.getName();
		String desFilePath = realsavepath + "temp/" + "encrypt";
		File encryptZipFile = fileCreate(desFile, desFilePath);
		try {
			AesZipFileEncrypter.zipAndEncryptAll(zipFile, encryptZipFile, passWord, new AESEncrypterBC());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return encryptZipFile;
	}

	
	/**
	 * 上传文件
	 * @param file
	 * @param request
	 */
	public static void upload(File file) {
		 ThirdProperties thirdProperties=ThirdPropertiesInitUtil.getThirdProperties();
		 String realsavepath=WriteDataUtil.class.getResource(thirdProperties.getImage_path()).getPath();
		FileInputStream inputStream;
		try {
			inputStream = new FileInputStream(file);
			//String realsavepath = request.getSession().getServletContext().getRealPath("");
			String name = file.getName().substring(0,
					file.getName().length() - file.getName().substring(file.getName().lastIndexOf(".")).length());
			String zipFilePath = realsavepath + "temp\\" + "zip";
			File logosavedir = new File(zipFilePath);
			
			if (!logosavedir.exists()) {
				logosavedir.mkdirs();
			}
			FileOutputStream fileStream = new FileOutputStream(new File(zipFilePath, name));
			byte[] bytes = new byte[1024];

			int numReadByte = 0;
			while ((numReadByte = inputStream.read(bytes)) > 0) {
				{
					fileStream.write(bytes, 0, numReadByte);
				}

			}
			//关闭输入输出流
			inputStream.close();
			fileStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 生成文件夹及文件
	 * @param fileStr
	 * @param filePath
	 * @return
	 */
	public static File fileCreate(String fileStr, String filePath) {
		File file = null;
		file = new File(filePath);
		// 判断路径是否存在
		if (!file.exists() && !file.isDirectory()) {
			MarvelsLogUtil.getInstance().info("==========>>>路径不存在");
			file.mkdir();
		} else {
			MarvelsLogUtil.getInstance().info("==========>>>路径已存在");
		}

		file = new File(fileStr);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			MarvelsLogUtil.getInstance().info("=========>>>文件已存在!");
		}
		return file;
	}
	
	
	/**
	 * 文件名:上传信用报告
	 * @param sign
	 * @return
	 */
	public static String getName(int sign){
		//普通上传报文
		if(sign == 1){
			SimpleDateFormat format=new SimpleDateFormat("yyyyMM");
			String date=format.format(new Date());
			String name=orgcode + date+RandomCode.getChar(3) + sign;
			return name;
		}
		// 删除报文
		if(sign == 8){
			SimpleDateFormat format=new SimpleDateFormat("yyyyMMdd");
			String date=format.format(new Date());
			String name=orgcode + date+RandomCode.getChar(1) + sign;
			return name;
		}
		return null;
	}
	
	
	/**
	 * 文件名:信用报告批量查询文件
	 * @return
	 */
	public static String getName(){
		SimpleDateFormat format=new SimpleDateFormat("yyyyMMdd");
		String date=format.format(new Date());
		String name=orgcode+date+RandomCode.getChar(2);
		return name;
	}
	
	
	/**
	 * 解压zip文件
	 * @param file
	 */
	public static void unzipFile(File file){
		long startTime=System.currentTimeMillis();  
        try {  
            ZipInputStream Zin=new ZipInputStream(new FileInputStream(file));//输入源zip路径  
            BufferedInputStream Bin=new BufferedInputStream(Zin);  
            String Parent="C:\\Users\\HAN\\Desktop"; //输出路径（文件夹目录）  
            File Fout=null;  
            ZipEntry entry;  
            try {  
                while((entry = Zin.getNextEntry())!=null && !entry.isDirectory()){  
                    Fout=new File(Parent,entry.getName());  
                    if(!Fout.exists()){  
                        (new File(Fout.getParent())).mkdirs();  
                    }  
                    FileOutputStream out=new FileOutputStream(Fout);  
                    BufferedOutputStream Bout=new BufferedOutputStream(out);  
                    int b;  
                    while((b=Bin.read())!=-1){  
                        Bout.write(b);  
                    }  
                    Bout.close();  
                    out.close();  
                    System.out.println(Fout+"解压成功");      
                }  
                Bin.close();  
                Zin.close();  
            } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
        } catch (FileNotFoundException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        long endTime=System.currentTimeMillis();  
        System.out.println("耗费时间： "+(endTime-startTime)+" ms");  
	}
}
